package pro.ticktock.tools.mbconv;

import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by lambert on 2017/10/30.
 */
public class FileMonitor {
  public static void main(String[] args) {

    File dir = new File(MusciBibleConverter.archiveDir);
    FileAlterationMonitor monitor = new FileAlterationMonitor();

    Set<String> fileSet = new HashSet<>(Arrays.asList(MusciBibleConverter.fileList));

    AtomicBoolean dirty = new AtomicBoolean(true);

    FileAlterationObserver observer = new FileAlterationObserver(dir, f -> fileSet.contains(f.getName()));

    observer.addListener(new FileAlterationListenerAdaptor() {
      public void onFileChange(File file) {
        super.onFileChange(file);
        System.out.println(file.getName()+" file changed");
        try {
          synchronized (dirty) {
            dirty.set(true);
            dirty.notifyAll();
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    });


    new Thread(() -> {
      while (true) {
        boolean needToScan = false;
        synchronized (dirty) {
          if (!dirty.get()) {
            try {
              dirty.wait();
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }

          if (dirty.get()) {
            needToScan = true;
            dirty.set(false);
          }
        }

        if (needToScan) {
          try {
            MusciBibleConverter.main(new String[0]);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
    }, "Executor").start();


    monitor.addObserver(observer);
    try {
      System.out.println("Observing: " + MusciBibleConverter.archiveDir);
      monitor.start();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
